package com.zide.system.controller;

import com.zide.common.annotation.Log;
import com.zide.common.constant.CacheConstants;
import com.zide.common.core.domain.CommonResult;
import com.zide.common.core.domain.entity.SysUser;
import com.zide.common.core.redis.RedisCache;
import com.zide.common.enums.BusinessType;
import com.zide.common.utils.SecurityUtils;
import com.zide.common.utils.StringUtils;
import com.zide.file.domain.vo.result.FileUploadResultVO;
import com.zide.file.service.IImageFileService;
import com.zide.system.domain.user.vo.save.SystemUserSaveVO;
import com.zide.system.service.ISysUserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.zide.common.core.domain.CommonResult.error;
import static com.zide.common.core.domain.CommonResult.success;

/**
 * 个人信息 业务处理
 *
 * @author zide
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController {
    @Resource
    private ISysUserService userService;
    @Resource
    private IImageFileService imageFileService;
    @Resource
    private RedisCache redisCache;

    /**
     * 个人信息
     */
    @GetMapping
    public CommonResult profile() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        CommonResult ajax = success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(user.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(user.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public CommonResult updateProfile(@RequestBody SystemUserSaveVO saveVO) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        user.setNickname(saveVO.getNickname());
        user.setEmail(saveVO.getEmail());
        user.setMobile(saveVO.getMobile());
        user.setSex(saveVO.getSex());
        if (StringUtils.isNotEmpty(saveVO.getMobile()) && !userService.checkPhoneUnique(saveVO)) {
            return error("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(saveVO.getEmail()) && !userService.checkEmailUnique(saveVO)) {
            return error("修改用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(user) > 0) {
            // 更新缓存用户信息
            redisCache.setCacheObject(CacheConstants.PRE_SYSUSER + user.getUserId(),user);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public CommonResult updatePwd(String oldPassword, String newPassword) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String username = user.getUsername();
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword,password)) {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword,password)) {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(username, newPassword) > 0) {
            // 更新缓存用户密码
            user.setPassword(newPassword);
            redisCache.setCacheObject(CacheConstants.PRE_SYSUSER + user.getUserId(),user);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public CommonResult avatar(@RequestParam("file") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            // 上传头像
            FileUploadResultVO uploadResult = imageFileService.uploadAvatar(file);
            String avatarUrl = uploadResult.getUrl();
            if (userService.updateUserAvatar(user.getUsername(), avatarUrl)) {
                // 更新缓存用户头像
                user.setAvatar(avatarUrl);
                redisCache.setCacheObject(CacheConstants.PRE_SYSUSER + user.getUserId(),user);
                return success().put("data",avatarUrl);
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
